<?php

namespace App\Console\Commands;

use App\Console\Commands\Common\CommonCommand;
use App\Models\Common\MyOffice;

class Watermark extends CommonCommand {

    protected $signature = 'word:watermark';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle() {

        $strKeyWord = file_get_contents(base_path('keyWord.txt'));
        $strKeyWord = str_replace('，', ',', $strKeyWord);
        $strKeyWord = str_replace("\r\n", '', $strKeyWord);
        $strKeyWord = str_replace("\n", '', $strKeyWord);
        $keyWords = array_filter(explode(',', $strKeyWord));

        $myWord = new MyOffice();
        $texts = [
            '联系小编：微信：ctbsc2021或ctbsc2022；QQ：2022879962',
            '微信免费公文发布交流群：添加小编拉您进群，备注加群。',
        ];
        $root = base_path('word');
        $words = scandir($root);
        unset($words[0]);
        unset($words[1]);
        $count = 0;
        //dd($words);
        foreach ($words as $word) {
            try{
                $source = $root.'/'.$word;
                if(is_dir($source))continue;
                $myWord->setSource($source);
                $myWord->loadWord();
                $myWord->addWaterMark(public_path('storage/qcode/wm.png'),5,20,360,17);
                $myWord->addTexts([]);
                $myWord->addImg(public_path('/storage/qcode/union.png'),5,5,450,170);
                $exportFolder = $root."/new";
                if (!file_exists($exportFolder)) mkdir($exportFolder, 0777, true);
                if(file_exists("$exportFolder/$word")){
                    dump("已经存在 $word");
                }else{
                    $doc = "$exportFolder/$word";
                    foreach ($keyWords as $keyWord) {
                        $doc = str_replace($keyWord, 'XXX', $doc);
                    }
                    $myWord->saveOffice($doc);
                }
                $this->info("成功 $word");
                $count++;
            }catch(\Exception $e){
                $this->error("失败！！！！！ $word,失败原因：".$e->getFile().':'.$e->getLine().':'.$e->getMessage());
            }
        }
        $this->warn("*****************************************************");
        //dump("*****************************************************");
        $this->warn("本次共计完成:".$count);
        return 0;
    }
}
